package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.SMSUtils;
import com.itheima.common.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/validatecode")
public class validatecodeController {
    @Autowired
    private RedisTemplate redisTemplate;

    public static final String ORDER_KEY = "预约验证码";
    public static final String LOGIN_KEY = "登录验证码";
    public static final String TemplateCode = "SMS_472965022";

    /**
     * 获取手机验证码
     * @param telephone
     * @return
     */
    @PostMapping("/send4Order")
    public Result send4Order(@RequestParam String telephone){
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        System.out.println("手机号为:"+telephone+"code：为"+code);
        //用hush 存储

        redisTemplate.opsForValue().set(ORDER_KEY+telephone,code);
        //验证时间只有5分钟
        redisTemplate.expire(telephone,300*1000, TimeUnit.MILLISECONDS);
        SMSUtils.sendMessage(TemplateCode,telephone,code);
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    /**
     * 获取登录验证码
     * @param telephone
     */
    @GetMapping("/send4Login")
    public Result send4Login(@RequestParam String telephone){
        String code = ValidateCodeUtils.generateValidateCode(6).toString();

        System.out.println("手机号为:"+telephone+"code：为"+code);
        //用hush 存储

        redisTemplate.opsForValue().set(LOGIN_KEY+telephone,code);
        //验证时间只有5分钟
        redisTemplate.expire(telephone,300*1000, TimeUnit.MILLISECONDS);
        SMSUtils.sendMessage(TemplateCode,telephone,code);
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

}
